/**
 * @Description: 接口请求封装
 * @Author: yuhao 1262172637@qq.com
 * @Date: 2024-03-02 10:09:11
 * @LastEditors: yuhao 1262172637@qq.com
 * @LastEditTime: 2024-03-02 10:56:23
 * @FilePath: /uniapp-android-pda-demo/request/request.js
 */
import { APIURL } from '@/utils/env.js';

/**
 * @description: 带Token请求
 * @param {PageURIString} url
 * @param {*} method 请求方法（大写）：GET|POST|PUT|DELETE
 * @param {*} data 请求携带的参数数据
 * @param {*} ContentType 请求头类型 'application/json; charset=UTF-8'|'application/x-www-form-urlencoded'
 * @param {*} showLoading 默认不显示接口请求状态
 * @return {*} Promise 
 */
const HttpRequest = (url, method, data, ContentType = 'application/json; charset=UTF-8', showLoading = false) => {
	// 此token是登录成功后后台返回保存在storage中的
	const token = "Bearer " + uni.getStorageSync('token');

	if (showLoading) {
		uni.showLoading({ title: '加载中' }); // 显示加载状态
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: APIURL + url,
			method: method,
			data: data,
			header: {
				'Authorization': token,
				'Content-Type': ContentType
			},
			timeout: 20000,
			dataType: 'json',
			success: (successData) => {
				// 如果有显示loading，则隐藏
				if (showLoading) {
					uni.hideLoading();
				}

				const res = successData.data
				if (res.code === 500 || res.status === 500) {
					console.log('接口请求报错', res);
					uni.$u.toast(res || '异常，请联系管理员');
					// 后端返回500错误就跳转登录
					// setTimeout(()=>{
					// 	uni.navigateTo({
					// 		url: '/pages/login/login'
					// 	});
					// }, 1500);
					reject(res)
				} else {
					resolve(res);
				}
			},
			fail: (error) => {
				// 如果有显示loading，则隐藏
				if (showLoading) {
					uni.hideLoading();
				}
				toast('网络连接失败，请稍后重试');
				console.log('接口请求报错', error);
				reject(error);
			}
		});
	})
};

export default HttpRequest